package controllers

import (
	"crypto/sha1"
	"database/sql"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	_ "github.com/go-sql-driver/mysql"
	"github.com/op/go-logging"
	"github.com/satori/go.uuid"
	"golang.org/x/xerrors"
	"io/ioutil"
)
var log = logging.MustGetLogger("example")
type AuthorityController struct {
	beego.Controller
}
type Auth struct {
	Username string `json:"username"`
	Password string `json:"password"`
	Team 	 string `json:"team"`
}
type AuthInfo struct {
	username string
	team string
	password []byte
	salt string
}
func (c *AuthorityController) Post() {
	bytes, err := ioutil.ReadAll(c.Ctx.Request.Body)
	if err != nil {
		panic(err)
	}
	var a *Auth
	err = json.Unmarshal(bytes, &a)
	if err != nil {
		fmt.Println(err)
	}
	salt, res := addSalt(a.Password)
	authInfo := &AuthInfo{
		username: a.Username,
		team:     a.Team,
		password: res,
		salt:     salt,
	}
	config := NewMySQLConfig()
	sdb, err := OpenSQL(config)
	err = InsertMySQL(authInfo, sdb)
	if err != nil {
		log.Errorf("insert data error")
	}
}

func addSalt(s string) (salt string, result []byte) {
	var err error
	u := uuid.Must(uuid.NewV4(), err)
	uuidStr := u.String()
	salt = uuidStr
	sha1in := uuidStr + s
	res := sha1.Sum([]byte(sha1in))
	result = res[:]
	return salt, result
}

func OpenSQL(config *SQLConfig) (*sql.DB, error) {
	return sql.Open(config.Schema, config.DBName)
}
func InsertMySQL(data interface{}, db *sql.DB) error {
	if val, ok := data.(AuthInfo); ok {
		err := insertAuthorityData(val, db)
		if err != nil {
			return xerrors.Errorf("insert authority data error", err)
		}
	}
	return xerrors.Errorf("data type is not match")
}

func insertAuthorityData(data AuthInfo, db *sql.DB) error {
	auth, err := db.Prepare(QueryTemplate[InsertAuthorityData])
	if err != nil {
		return xerrors.Errorf("err is : %w", err)
	}
	res, err := auth.Exec(data.username, data.password, data.salt)
	if err != nil {
		return xerrors.Errorf("err is : %w", err)
	}
	log.Info(res)
	return nil
}
